package com.project.im.common.exception;

import com.project.im.app.vo.ResponseVO;
import com.project.im.common.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(WebException.class)
    public ResponseVO<?> handleWebException(WebException e) {
        log.error("【业务异常】异常信息: {}", e.getMessage());
        return ResponseVO.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseVO<?> handleAuthenticationException(AuthenticationException e) {
        log.error("【认证异常】异常信息: {}", e.getMessage());
        return ResponseVO.fail(ResponseCode.AR100);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseVO<?> handleAccessDeniedException(AccessDeniedException e) {
        log.error("【鉴权异常】异常信息: {}", e.getMessage());
        return ResponseVO.fail(ResponseCode.PR100);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVO<?> handleValidationExceptions(MethodArgumentNotValidException e) {
        String message = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        log.error("【参数异常】异常信息: {}", message);
        return ResponseVO.fail(ResponseCode.PARAM_ERROR, message);
    }

    @ExceptionHandler(Exception.class)
    public ResponseVO<?> handleException(Exception e) {
        log.error("【全局异常】异常信息: {}", e.getMessage(), e);
        return ResponseVO.fail(ResponseCode.UNKNOWN_ERROR);
    }
}
